<?php

namespace App\Admin\Controllers;

use App\Admin\Renderable\GoodsTable;
use App\Admin\Repositories\GrLive;
use App\Admin\Support\GoodsInfo;
use App\Models\GrGood;
use App\Models\GrUser;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class GrLiveController extends AdminController
{

    public function __construct()
    {
        $user = GrUser::all()->toArray();
        $userInfo = [];
        foreach ($user as $val) {
            $userInfo[$val['id']] = $val['real_name'];
        }
        $this->user = $userInfo;
    }


    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new GrLive(['userInfo']), function (Grid $grid) {

            $grid->column('live_id')->sortable();
            $grid->column('live_title');
            $grid->column('live_about');
            $grid->column('live_img_cover')->image();
            $grid->column('live_type')->display(function ($info) {
                if ($info == 1) {
                    return '竖屏直播';
                } else {
                    return '横屏直播';
                }
            });
            $grid->column('live_goods_id', '出售商品')->display('详情')->expand(function () {
                $goodsId = $this->live_goods_id;

                $goodsId = explode(',', $goodsId);

                // 允许在闭包内返回异步加载类的实例
                return GoodsInfo::make(['id' => $goodsId]);
            });
            $grid->column('userInfo.real_name', '主播名字');
            $grid->column('', '直播地址')->display('走你')->link(function () {
//                $live =[
//                    'play_url'=>$this->play_url,
//                    'live_id'=>$this->live_id
//                ];
//                $user=[
//                    'real_name'=>'超级管理员'
//                ];

                switch ($this->live_status) {
                    case 1:
                        return admin_url('adminLive?live_id=' . $this->live_id . '&user_id=' . '0');
                    case 2:
                        return admin_url('liveError?status=2');
                    case 3:
                        return admin_url('liveError?status=3');
                    case 0:
                        return admin_url('liveError?status=0');
                }


            });
            $grid->column('live_status')->display(function ($info) {
                if ($info == 1) {
                    return '直播中';
                } elseif ($info == 2) {
                    return '已结束';
                } elseif ($info == 3) {
                    return '暂停';
                } elseif ($info == 0) {
                    return '未开始';
                }
            })->filter(
                Grid\Column\Filter\In::make([
                    0 => '未开始',
                    1 => '直播中',
                    2 => '已结束',
                    3 => '暂停',
                ])
            );
            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('live_id');

            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new GrLive(), function (Show $show) {
            $show->field('live_id');
            $show->field('live_title');
            $show->field('live_about');
            $show->field('live_img_cover');
            $show->field('live_type');
            $show->field('live_goods_id');
            $show->field('user_id');
            $show->field('live_status');
            $show->field('begin_time');
            $show->field('end_time');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new GrLive(), function (Form $form) {
            $form->display('live_id');
            $form->text('live_title')->required()->help('直播标题限制50字，限制汉字、数字、英文字母');
            $form->textarea('live_about')->help('填写直播描述，限制300字，限制汉字、数字、英文字母');
            $form->image('live_img_cover')->uniqueName()->autoUpload()->required()->width(3)->move('liveImgCover');;
            $form->radio('live_type')->options(['1' => '竖屏模式', '2' => '横屏模式']);
            $form->select('user_id')->options($this->user);

            $form->radio('live_time', '直播类型')->when(1, function (Form $form) {
//               $form->datetime('begin_time')->default(date('Y-m-d H:i:s'));
            })
                ->when(2, function (Form $form) {
                    $form->datetimeRange('begin_time', 'end_time');
                })
                ->options([
                    1 => '立即直播',
                    2 => '预定直播',
                ])
                ->default(1);
//            $form->datetimeRange('begin_time','end_time');
            $form->radio('live_status')->options(['1' => '直播中', '2' => '已结束', '3' => '暂停'])->default(0);
            $form->multipleSelectTable('live_goods_id', '选择商品')
                ->title('选择商品')
                ->from(GoodsTable::make())
                ->model(GrGood::class, 'goods_id', 'goods_name')->saving(function ($v) {
                    // 转为 , 隔开的字符串
                    return implode(',', $v);
                });
            $form->display('created_at');
            $form->display('updated_at');

            $form->saving(function (Form $form) {
                // 判断是否是新增操作
                if ($form->isCreating()) {
                    $data = $form->input();
//                    dd($data);
                    $live_time = $data['live_time'];
                    $form->input('live_goods_id', json_encode($data['live_goods_id']));
                    if ($live_time == 1) {
                        $form->live_status = 1;
                        $form->input('begin_time', date('Y-m-d H:i:s'));
                        $form->input('end_time', '2023-01-01 00:00:00');
                    } else {
                        $form->input('live_status', 0);
                    }


                }
            });

            $form->saved(function (Form $form, $result) {
                // 判断是否是新增操作
                if ($form->isCreating()) {
                    // 自增ID
                    $newId = $result;
                    $data = $form->input();
                    if ($data['live_time'] == 2) {
                        $txTime = strtoupper(base_convert(strtotime($data['end_time']), 10, 16));
                    } else {
                        $txTime = strtoupper(base_convert(strtotime('2023-01-01 00:00:00'), 10, 16));
                    }

                    //txSecret = MD5( KEY + streamName + txTime )
                    $streamName = mt_rand();
                    $txSecret = md5(env('LIVE_STREAMING_KEY') . $streamName . $txTime);
                    $ext_str = "?" . http_build_query(array(
                            "txSecret" => $txSecret,
                            "txTime" => $txTime
                        ));
                    // 推流地址
                    $streamingUrl = env('LIVE_STREAMINGURL') . $streamName . $ext_str;

                    // 生成播流地址信息
                    $streamName = $streamName . '.m3u8';
                    // 拼接播流地址
                    $playUrl = env('LIVE_PLAY_URL') . $streamName;
                    // 将推流播流地址放入数据库
                    \App\Models\GrLive::where('live_id', $newId)->update(['streaming_url' => $streamingUrl, 'play_url' => $playUrl]);
                    // 拼接直播号
                    $liveNo = $newId . $streamName;
                    $info = [
                        'play_url' => $playUrl,
                        'watch_num' => 0,
                        'love_num' => 0,
                        'user_id' => $data['user_id']
                    ];
                    // 也可以这样获取自增ID
                    $newId = $form->getKey();
                    if (!$newId) {
                        return $form->error('数据保存失败');
                    }
                }
            });
        });
    }

    public function adminLive(Request $request)
    {
        $live_id = $request->get('live_id');
        $user_id = $request->get('user_id');
        $live = \App\Models\GrLive::where('live_id', $live_id)->select('play_url', 'live_id')->get()->toArray()[0];

        if ($user_id == 0) {
            $user['real_name'] = '超级管理员';
        } else {
            $user = GrUser::where('id', $user_id)->select('real_name')->get()->toArray()[0];
        }

        return view('adminLive', compact('user', 'live'));
    }

    public function liveError(Request $request)
    {
        $status = $request->get('status');
        if ($status == 0) {
            return '直播未开始';
        } elseif ($status == 2) {
            return '直播已结束';
        } else {
            return '直播暂停';
        }
    }
}
